import { defineStore } from 'pinia';
import { store } from '/@/store';
import { DeckConfigData, CreateDeck, DeckInfoItem } from '/@/api/currentDeck/model/deckModel';
import { cloneDeep } from 'lodash-es';

interface IState {
  gameId: string; // 游戏ID
  deckConfig: DeckConfigData; // 套牌配置
  cardGroup: DeckConfigData['card_group']; // 套牌配置-组牌配置
  createDeckParams: CreateDeck; // 创建/修改套牌的参数
}

interface IGetter {
  getGameId: (state: IState) => string;
  getDeckConfig: (state: IState) => DeckConfigData;
  getCardGroup: (state: IState) => DeckConfigData['card_group'];
  getCreateDeckParams: (state: IState) => CreateDeck;
  [propName: string]: ((state: IState) => IState | unknown) | (() => void);
}

interface IActions {
  setGameId: (gameId: string) => void;
  setDeckConfig: (configs: DeckConfigData) => void;
  setCardGroup: (cardGroup: DeckConfigData['card_group']) => void;
  setDeckId: (deckId: number) => void;
  setDeckInfo: (deckInfo: DeckInfoItem[]) => void;
  clearCreateDeckParams: () => void;
}

export const useCurrentDeckStore = defineStore<'app_current_deck', IState, IGetter, IActions>({
  id: 'app_current_deck',
  state: () => {
    return {
      gameId: '',
      deckConfig: {} as DeckConfigData,
      cardGroup: [],
      createDeckParams: {
        game_id: '',
        deck_id: 0,
        deck_name: '',
        deck_desc: '',
        deck_info: [],
        is_open: 0,
        tags: [],
      },
    };
  },
  getters: {
    getGameId: (state) => {
      return state.gameId;
    },
    getDeckConfig: (state) => {
      return state.deckConfig;
    },
    getCardGroup: (state) => {
      return state.cardGroup;
    },
    getCreateDeckParams: (state) => {
      return state.createDeckParams;
    },
  },

  actions: {
    setGameId(gameId: string) {
      this.gameId = gameId;
    },
    setDeckConfig(configs) {
      this.deckConfig = cloneDeep(configs);
    },
    setCardGroup(cardGroup) {
      this.cardGroup = cardGroup;
    },
    setDeckId(deckId) {
      this.createDeckParams.deck_id = deckId;
    },
    setDeckInfo(deckInfo) {
      this.createDeckParams.deck_info = cloneDeep(deckInfo);
    },
    clearCreateDeckParams() {
      this.createDeckParams.game_id = this.gameId;
      this.createDeckParams.deck_id = 0;
      this.createDeckParams.deck_name = '';
      this.createDeckParams.deck_desc = '';
      this.createDeckParams.deck_info.length = 0;
      this.createDeckParams.is_open = 0;
      this.createDeckParams.tags = [];
      const initDeckInfo: DeckInfoItem[] = [];
      for (const item of this.getCardGroup) {
        initDeckInfo.push({
          group_name: item.group_name,
          card_number: 0,
          card_list: [],
        });
      }
      this.createDeckParams.deck_info = cloneDeep(initDeckInfo);
    },
  },
});

// Need to be used outside the setup
export function useCurrentDeckStoreWithOut() {
  return useCurrentDeckStore(store);
}
